package es.manuel.maa.validator;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

import es.manuel.maa.service.UserService;
import es.manuel.maa.service.impl.UserServiceImpl;
import es.manuel.maa.util.JSFUtil;

public class UsernameValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		WebApplicationContext webApplicationContext = FacesContextUtils
				.getRequiredWebApplicationContext(context);
		UserService userService = webApplicationContext.getBean(
				UserServiceImpl.ID, UserService.class);

		if (!userService.isUsernameAvailable((String) value)) {
			FacesMessage message = JSFUtil.getMessage("msg",
					"user.validation.username.unavailable",
					FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
	}

}
